<?php

namespace app\index\controller;

use app\admin\model\PohtoMenuModel;
use app\admin\validate\CommonnValidate;
use app\BaseController;
use app\index\model\PhotoList as PhotoListModal;
use app\index\model\PohtoListImage;

class PhotoMenu extends BaseController
{
    protected $middleware = [
        'Auth' => ['except' => ['list', 'allList']]
    ];
    public function allList()
    {
        $params = $this->request->get(['photo_id']);
        $sql = new PohtoMenuModel();
        $whereArr[] = ["photo_id", "=", $params['photo_id']];
        $list = $sql->where($whereArr)->order('sort asc')
            ->order('create_at asc')->select();
        return result()->success($list);
    }

    public function list() {
        $params = $this->request->post(['current', 'size', 'photo_id']);
        $validate = new CommonnValidate();
        if (!$validate->scene('list')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new PohtoMenuModel();
        $whereArr[] = ["photo_id", "=", $params['photo_id']];
        $list = $sql
            ->where($whereArr)
            ->order('sort asc')
            ->order('create_at asc')
            ->paginate([
                'list_rows'=> request()->param('size'),
                'page' => request()->param('current'),
            ])->toArray();
        return result()->success($list);
    }

    public function getImg()
    {
        $params = $this->request->post(['menu_id']);
        $sql = new PohtoMenuModel();
        $info = $sql->find($params['menu_id']);
        if(empty($info)) {
            return result()->fail('数据不存在', 500);
        }
        $sqlList = new PhotoListModal();
        $photoInfo = $sqlList->find($info['photo_id']);
        $buy = false;
        if($photoInfo->price == 0) {
            $buy = true;
        } else if(!empty($this->request->user)) {
            $buy = $this->request->user->checkBuyPhoto($photoInfo['id']);
        }
        if($buy) {
            $imgSql = new PohtoListImage();
            $whereArr[] = ["menu_id", "=", $params['menu_id']];
            $list = $imgSql
                ->where($whereArr)
                ->order('sort asc')
                ->order('create_at asc')
                ->select();
            return result()->success($list);
        } else {
            return result()->fail('请购买后查看', 500);
        }
    }
}